<template>
	<div>
		<el-upload ref="uploadRef" class="upload my-add-hide" :action="$http.upFileUrl" :data="uploadData"
			:on-success="uploadSuccessHandle" :on-error="errorHandle" :on-change="changeHandle"
			:before-upload="beforeUpload" :headers="headers" :on-progress="progressHandle"
			:list-type="drag?'text':listType" :limit="limit" :class="{disabled:fileList.length >= limit}"
			:file-list="fileList" :accept="accept" :auto-upload="autoUpload" :drag="drag" :disabled="disabled">
			<el-icon>
				<component :is="drag?'UploadFilled':'Plus'"></component>
			</el-icon>
			<div v-if="drag" class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
			<template #file="{ file }">
				<img class="el-upload-list__item-thumbnail" :src="file.url" alt="" v-if="isImg(file)"></img>
				<div v-else
					style="text-align: center;display: flex;align-items: center;flex-direction: column;margin-top: 10px;justify-content: center;width: 100%;">
					<div><el-icon style="font-size: 40px;">
							<Document />
						</el-icon></div>
					<div>{{file.type}}文件</div>
				</div>
				<span class="el-upload-list__item-actions">
					<span class="el-upload-list__item-preview" v-if="isImg(file)"
						@click="handlePictureCardPreview(file)">
						<el-icon>
							<ZoomIn />
						</el-icon>
					</span>
					<span class="el-upload-list__item-delete" @click="handleDownload(file)">
						<el-icon>
							<Download />
						</el-icon>
					</span>
					<span class="el-upload-list__item-delete" @click="handleRemove(file)">
						<el-icon>
							<Delete />
						</el-icon>
					</span>
				</span>
				<span v-if="file.percent && file.percent != 0">
					<el-progress style="width: 100%;background-color: #00000094;color: white;font-size: 17px;"
						:stroke-width="8" :width="100" type="circle" :percentage="file.percent"
						text-color="#fff"></el-progress>
				</span>
			</template>
			<div slot="tip" class="el-upload__tip">
				<slot name="tip">
					{{tip}}
				</slot>
			</div>
		</el-upload>

		<el-image-viewer style="z-index: 9999;" v-if="yulanData.isShow" :initial-index="yulanData.index"
			@close="yulanCloseClick" :url-list="yulanData.urlList"></el-image-viewer>
	</div>
</template>
<script>
	import {
		saveAs
	} from 'file-saver'

	export default {
		components: {},
		name: "gz-upload",
		emits: ['update:modelValue'],
		props: {
			rootPath: {
				type: String,
				default: ""
			},
			modelValue: {
				type: [String, Array],
				default () {
					return "";
				},
			},
			accept: {
				default: "image/*"
			},
			limit: {
				default: 1
			},
			tip: {
				// default:"只能上传jpg/png文件，且不超过500kb"
			},
			maxSize: {
				type: String,
				default: '5m' //单位kb,m,g
			},
			drag: {
				default: false
			},
			listType: {
				default: "picture-card"
			},
			autoUpload: {
				default: true
			},
			disabled: {
				default: false
			}
		},
		data() {
			return {
				headers: {},
				uploadData: {
					rootPath: ""
				},
				fileList: [],
				yulanData: {
					isShow: false,
					urlList: [],
					index: 0
				}
			};
		},
		mounted() {
			this.uploadData.rootPath = this.rootPath
			this.headers = this.$http.uploadHeaders()
			setTimeout(()=>{
				this.initValue()
			},500)
		},
		methods: {
			initValue() {
				this.fileList = []
				if (this.modelValue) {
					if (this.limit > 1) {
						if (Array.isArray(this.modelValue)) {
							this.modelValue.forEach((item, index) => {
								let fileName = item.substr(item.lastIndexOf('/') + 1)
								this.fileList.push({
									name: fileName,
									url: item,
									uid: index,
									type: this.getType(fileName)
								})
							})
						} else {
							this.modelValue.split(",").forEach((item, index) => {
								let fileName = item.substr(item.lastIndexOf('/') + 1)
								this.fileList.push({
									name: fileName,
									url: item,
									uid: index,
									type: this.getType(fileName)
								})
							})
						}
					} else {
						let fileName = this.modelValue.substr(this.modelValue.lastIndexOf('/') + 1)
						this.fileList.push({
							name: fileName,
							url: this.modelValue,
							uid: 1,
							type: this.getType(fileName)
						})
					}
				}

				this.yulanData.urlList = this.fileList.filter(item => ['png', 'jpg', 'jpeg', 'webp', 'gif', 'ico']
					.includes(
						item.type)).map(item => item.url)
			},
			//上传添加图片
			uploadSuccessHandle(res, file, fileList) {
				if (!this.autoUpload) {
					this.$emit("on-success", response, file, fileList)
					return
				}
				if (res.success) {
					this.$common.msgSuccess('上传成功');
					file.type = res.result.type
					file.url = res.result.url
				} else {
					this.$common.msgError('上传失败');
				}
				file.percent = 0
			},
			//上传文件之前钩子事件
			beforeUpload(file) {
				if (!this.maxSize) {
					return
				}
				let maxSize = 0
				if (this.maxSize.indexOf("kb") != -1) {
					maxSize = 1024 * this.maxSize.substring(0, this.maxSize.length - 2)
				} else if (this.maxSize.indexOf("m") != -1) {
					maxSize = 1024 * 1024 * this.maxSize.substring(0, this.maxSize.length - 1)
				} else if (this.maxSize.indexOf("g") != -1) {
					maxSize = 1024 * 1024 * 1024 * this.maxSize.substring(0, this.maxSize.length - 1)
				}
				const isLtSize = file.size < maxSize;
				if (!isLtSize) {
					this.$common.msgWarn('文件大小不能超过 ' + this.maxSize + '!');
				}
				return isLtSize;
			},
			changeHandle(file, fileList) {
				this.fileList = fileList
				if (this.limit > 1) {
					this.$emit("update:modelValue", this.fileList.map(item => item.url).join(","));
				} else {
					this.$emit("update:modelValue", file.url);
				}
				this.yulanData.urlList = this.fileList.filter(item => ['png', 'jpg', 'jpeg', 'webp', 'gif', 'ico']
					.includes(item.type)).map(item => item.url)
			},
			progressHandle(event, file, fileList) {
				file.percent = parseInt(event.percent)
			},
			errorHandle(event, file, fileList) {
				file.percent = 0
			},
			//移除图片
			handleRemove(file) {
				console.log(file);
				let index = this.fileList.findIndex(item => item.uid == file.uid)
				if (index >= 0) {
					this.fileList.splice(index, 1)
				}
			},
			handlePictureCardPreview(file) {
				console.info("this.fileList", this.fileList)
				this.yulanData.index = this.fileList.findIndex(item => item.uid == file.uid)
				this.yulanData.isShow = true
			},
			handleDownload(file) {
				console.log(file);
				saveAs(file.url, file.name)
			},
			yulanCloseClick() {
				this.yulanData.isShow = false
			},
			getType(fileName) {
				let index = fileName.lastIndexOf(".");
				let ext = fileName.substr(index + 1);
				return ext.toLowerCase();
			},
			isImg(file) {
				console.info("file", file)
				if (file) {
					return ['png', 'jpg', 'jpeg', 'webp', 'gif', 'ico'].includes(file.type)
				} else {
					return false
				}
			},
		},
	};
</script>

<style lang="scss" scoped>
	.disabled :deep(.el-upload--picture-card) {
		display: none;
	}

	:deep(.el-upload-list__item) {
		transition: none !important;
	}

	:deep(.el-progress__text) {
		color: white;
		font-size: 17px;
	}
</style>